package com.dayuan.realm;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.dayuan.bean.BackRole;
import com.dayuan.bean.BackUser;
import com.dayuan.service.AdminUserService;
import com.dayuan.utils.PatternUtils;

//自定义 realm
public class MyShiroRealm extends AuthorizingRealm {

	private static final String REALM_NAME = "my_realm";

	@Resource
	private AdminUserService adminUserService;

	/***
	 * 获取授权信息
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pc) {
		// 根据自己系统规则的需要编写获取授权信息，这里为了快速入门只获取了用户对应角色的资源url信息
		BackUser backUser = (BackUser) pc.fromRealm(getName()).iterator().next();

		BackUser adminUser = new BackUser();
		if (PatternUtils.isEmail(backUser.getUserName())) {
			adminUser.setEmail(backUser.getUserName());
		} else {
			adminUser.setUserName(backUser.getUserName());
		}
		BackUser result = adminUserService.selectAdminUser(adminUser);

		List<BackRole> role = adminUserService.selectPermission(result.getId());
		
		Set<String> roles = new HashSet<String>();
		
		for (BackRole adminRole : role) {
			roles.add(adminRole.getName());
		}
		return new SimpleAuthorizationInfo(roles);
	}

	/***
	 * 获取认证信息
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken at) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) at;
		// 通过表单接收的用户名
		// String username = token.getUsername();

		BackUser adminUser = new BackUser();
		if (PatternUtils.isEmail(token.getUsername())) {
			adminUser.setEmail(token.getUsername());
		} else {
			adminUser.setUserName(token.getUsername());
		}

		adminUser.setPassword(String.valueOf(token.getPassword()));

		BackUser adminUserResult = adminUserService.selectAdminUser(adminUser);

		if (adminUserResult == null || !adminUserResult.getPassword().equals(adminUser.getPassword())) {
			throw new AuthenticationException("用户名或密码不正确！");
		}

		SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(adminUserResult,
				String.valueOf(token.getPassword()), getName());

		return simpleAuthenticationInfo;
	}

	@Override
	public String getName() {
		return REALM_NAME;
	}

}